package com.example.springbootusecase.hardware;


import javax.speech.Central;
import javax.speech.synthesis.Synthesizer;
import javax.speech.synthesis.SynthesizerModeDesc;
import java.util.Locale;

public class SpeakerExample {
    public static void main(String[] args) {
        try {
            // 设置语音合成引擎
            System.setProperty("freetts.voices", "com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory");

            // 注册引擎
            Central.registerEngineCentral("com.sun.speech.freetts.jsapi.FreeTTSEngineCentral");

            // 创建语音合成器
            Synthesizer synthesizer = Central.createSynthesizer(new SynthesizerModeDesc(Locale.US));

            // 分配资源和启动
            synthesizer.allocate();
            synthesizer.resume();

            // 设置语速、音量和音高
            synthesizer.getSynthesizerProperties().setSpeakingRate(150.0f);
            synthesizer.getSynthesizerProperties().setVolume(1.0f);
            synthesizer.getSynthesizerProperties().setPitch(100.0f);

            // 合成并播放文本
            synthesizer.speakPlainText("Hello", null);
            synthesizer.speakPlainText("you are welcome to my world", null);
            // 等待语音合成完成
            synthesizer.waitEngineState(Synthesizer.QUEUE_EMPTY);

            // 释放资源
            synthesizer.deallocate();

            System.out.println("文本转语音完成！");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}